const { http } = require("../../../utils/http");

// my/pages/Register/Register.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userName: '',
    nickName: '',
    email: '',
    phonenumber: '',
    sex: 0,
    sexOptions: ['男', '女', '未知','沃尔玛购物袋'],
    avatar: '',
    password: '',
    status: '0',
    delFlag: '0',
    loginIp: '',
    pwdUpdateDate: '',
    roleIds: [100],
    
    // 表单验证状态
    formErrors: {},
    isSubmitting: false
  },

  // 输入事件处理
  inputUserName(e) { 
    this.setData({ 
      userName: e.detail.value,
      'formErrors.userName': ''
    }); 
  },
  
  inputNickName(e) { 
    this.setData({ 
      nickName: e.detail.value,
      'formErrors.nickName': ''
    }); 
  },
  
  inputEmail(e) { 
    this.setData({ 
      email: e.detail.value,
      'formErrors.email': ''
    }); 
  },
  
  inputPhone(e) { 
    this.setData({ 
      phonenumber: e.detail.value,
      'formErrors.phonenumber': ''
    }); 
  },
  
  onSexChange(e) { 
    this.setData({ 
      sex: Number(e.detail.value),
      'formErrors.sex': ''
    }); 
  },
  
  inputPassword(e) { 
    this.setData({ 
      password: e.detail.value,
      'formErrors.password': ''
    }); 
  },

  // 选择头像
  chooseAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        // 显示加载提示
        wx.showLoading({
          title: '上传中...',
          mask: true
        });
        
        // 这里可以调用上传接口，暂时直接设置本地路径
        this.setData({
          avatar: tempFilePath
        });
        
        wx.hideLoading();
        wx.showToast({
          title: '头像设置成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        console.error('选择图片失败:', err);
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  },

  // 表单验证
  validateForm() {
    const errors = {};
    
    if (!this.data.userName.trim()) {
      errors.userName = '请输入用户名';
    } else if (this.data.userName.length < 3) {
      errors.userName = '用户名至少3个字符';
    }
    
    if (!this.data.nickName.trim()) {
      errors.nickName = '请输入昵称';
    }
    
    if (!this.data.email.trim()) {
      errors.email = '请输入邮箱';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.data.email)) {
      errors.email = '请输入有效的邮箱地址';
    }
    
    if (!this.data.phonenumber.trim()) {
      errors.phonenumber = '请输入手机号';
    } else if (!/^1[3-9]\d{9}$/.test(this.data.phonenumber)) {
      errors.phonenumber = '请输入有效的手机号';
    }
    
    if (!this.data.password.trim()) {
      errors.password = '请输入密码';
    } else if (this.data.password.length < 6) {
      errors.password = '密码至少6个字符';
    }
    
    this.setData({ formErrors: errors });
    return Object.keys(errors).length === 0;
  },

  // 提交注册
  submitRegister() {
    if (this.data.isSubmitting) return;
    
    if (!this.validateForm()) {
      wx.showToast({
        title: '请完善表单信息',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    this.setData({ isSubmitting: true });
    
    const now = new Date();
    const pad = n => n < 10 ? '0'+n : n;
    const dateStr = `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
    
    const data = {
      userName: this.data.userName.trim(),
      nickName: this.data.nickName.trim(),
      email: this.data.email.trim(),
      phonenumber: this.data.phonenumber.trim(),
      sex: String(this.data.sex),
      avatar: this.data.avatar.trim() || '/images/default-avatar.png',
      password: this.data.password,
      status: this.data.status,
      delFlag: this.data.delFlag,
      loginIp: this.data.loginIp,
      pwdUpdateDate: dateStr,
      roleIds: this.data.roleIds
    };
    
    wx.showLoading({ 
      title: '注册中...',
      mask: true
    });
    
    http.post('/system/user/addNew', data)
      .then(res => {
        wx.hideLoading();
        this.setData({ isSubmitting: false });
        
        if ((res.code !== undefined && (res.code === 0 || res.code === 200)) || res.success) {
          wx.showToast({ 
            title: '注册成功', 
            icon: 'success',
            duration: 2000
          });
          
          // 延迟返回，让用户看到成功提示
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            });
          }, 1500);
        } else {
          wx.showModal({ 
            title: '注册失败', 
            content: res.msg || res.message || '请重试', 
            showCancel: false 
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        this.setData({ isSubmitting: false });
        
        console.error('注册失败:', err);
        wx.showModal({ 
          title: '网络错误', 
          content: err.message || '请检查网络后重试', 
          showCancel: false 
        });
      });
  },

  // 清空表单
  clearForm() {
    this.setData({
      userName: '',
      nickName: '',
      email: '',
      phonenumber: '',
      sex: 0,
      avatar: '/images/我的.png',
      password: '',
      formErrors: {}
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 设置默认头像
    if (!this.data.avatar) {
      this.setData({
        avatar: '/images/default-avatar.png'
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '在线学习平台 - 用户注册',
      path: '/my/pages/Register/Register'
    };
  }
})